package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.pojo.Dish;
import com.itheima.dto.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish>
                implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //1 将菜品的基本信息保存到菜品表dish
        this.save(dishDto);
        Long dishId = dishDto.getId();

        //2 菜品的口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //3 将菜品的口味保存到菜品口味表"dish_flavor"
        dishFlavorService.saveBatch(flavors);
    }

    @Override // 菜品修改第一步 -> 在修改框对菜品信息进行回显
    public DishDto getByIdWithFlavor(Long id) {
        //1 通过dish数据表查询菜品的基本信息
        Dish byId = this.getById(id);
        // 创建对象
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId,dishDto);

        //2 通过dish_flavor数据表查询出对应菜品的口味信息
        // 创建条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        queryWrapper.eq(DishFlavor::getDishId,byId.getId());
        // 调用方法完成查询 通过集合的方式展示
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        // 封装查询结果并返回
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional // 菜品修改第二步 -> 对菜品信息进行修改
    public void updateWithFlavor(DishDto dishDto) {
        //1 对dish数据表的信息进行更新
        this.updateById(dishDto);

        //2 删除dish_flavor数据表的菜品对应口味信息
        // 创建条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        // 添加条件
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        // 调用方法进行删除
        dishFlavorService.remove(queryWrapper);

        //3 在dish_flavor数据表中添加当前提交的数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        // 对数据进行封装
        dishFlavorService.saveBatch(flavors);
    }
}
